import sun.management.counter.Units;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author Stringzhua
 * @Date 2024/10/30 14:16
 * description:
 */
public class ThreadPool03 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //向线程池提交10个线程任务
        for (int i = 0; i < 10; i++) {
            final int j = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "执行线程任务" + j);

                    //这里休眠2s
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        //关闭线程池,等待线程池任务执行完毕后关闭线程池
        executorService.shutdown();
        /**
         * awaitTermination(时间值),在指定时间值后,对线程池的关闭状态进行检查
         * 返回值为true,线程池已经关闭
         * 返回值为false,线程池尚未关闭
         */
        try {
            //每隔3s检查线程池关闭状态
//            while (!executorService.awaitTermination(3, TimeUnit.SECONDS)) {
//                System.out.println("线程池尚未关闭");
//            }

            //3秒钟后立即关闭线程池
            if (!executorService.awaitTermination(3, TimeUnit.SECONDS)) {
                //立即关闭
                executorService.shutdownNow();
            }


        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("线程池已经关闭");

    }
}
